'use strict';

const Service = require('egg').Service;

class UserService extends Service {
    /**
     * 查询用户
     *
     * @param {String} id @default null -用户id 传入此值后传入的其他值将失效
     * @param {String} username @default null -用户名 传入此值后传入的其他值将失效
     * @param {Number} page @default 1 -当前页
     * @param {Number} currentPage @default 10 -返回条数
     * @param {String} select @default null -要显示的key
     */
    async find(
        {
            id,
            username,
            name = '',
            page = 1,
            state = null,
            sort = -1,
            sex = '',
            role = null,
            phone = '',
            weixin = '',
            currentPage = 10
        } = {},
        select = null) {
        const { ctx } = this;

        if (id) {
            return await ctx.model.User.findById(id).populate('role', 'name id').select(select);
        } else {
            let querys = {
                state: {
                    $ne: 0
                }
            };

            state ? querys.state = state : true
            username ? querys.username = username : true
            sex ? querys.sex = sex : true;
            phone ? querys.phone = phone : true;
            weixin ? querys.weixin = weixin : true;
            role ? querys.role = { $in: role } : true;

            const res = await ctx.model.User
                .find(querys)
                .regex('name', new RegExp(name, 'i'))
                .populate('role', 'name id')
                .sort({ createAt: sort })
                .skip((Number(page) - 1) * Number(currentPage))
                .limit(Number(currentPage))
                .select(select);
            const count = await ctx.model.User
                .find(querys)
                .regex('name', new RegExp(name, 'i'))
                .count();
                console.log(page)
                console.log(count)
                console.log(res)
            return {
                count,
                page,
                list: res
            }
        }
    }

    /**
     * 查询超级用户
     *
     */
    async findRoot() {
        const { ctx } = this;
        return await ctx.model.User.findOne({ root: true });
    }


    /**
     * 新增用户
     *
     * @param {String} username -用户名/邮箱账号
     * @param {String} password -密码
     */
    async create({ username, state = '1', name = null, sex = '未知', phone = '', summary = '', headImg = '', email = '', weixin = '', password = '', root = false } = {}) {
        const { ctx, app } = this;
        
        const user = await ctx.model.User.findOne({ username });
        if (user) {
            ctx.throw(402, '用户名已被注册');
        }
        let role = [];
        console.log('添加角色')
        console.log(app.custom.role)
        if (!root) {
            role.push(app.custom.role.ordinarylRole)
        }
        console.log(role)
        return await ctx.model.User.create({
            username,
            name,
            password,
            sex,
            phone,
            weixin,
            root,
            role,
            state,
            summary,
            headImg,
            email,
        });
    }

    /**
     * 修改/删除用户
     *
     * @param {String} id -用户id
     * @param {Object} payload -修改条件
     */
    async update(id, payload = {}) {
        const { ctx, app } = this;
        const user = await ctx.model.User.findById(id);
        if (!user) {
            ctx.throw(404, '用户不存在');
        }

        if ([0, 2].includes(payload.status)) {
            if (id === app.custom.admin.id) {
                ctx.throw(402, '不允许变更管理员状态');
            }
        }
        console.log(payload.state)
        payload.updateAt = Date.now();
        return await ctx.model.User.findByIdAndUpdate(id, payload);
    }

    /**
     * 刷新/新增用户token
     *
     * @param {String} id -用户id
     * @param {String} token -用户toekn
     */
    async updateToken(id, token) {
        return await this.ctx.model.User.findByIdAndUpdate(id, { token });
    }

    /**
     * 为用户添加/移除角色
     *
     * @param {String} userId -用户id
     * @param {String} roleId -角色id
     * @param {Boolean} destroy @default false -是否移除，默认新增
     */
    async userAndRole(userId, roleId, destroy = false) {
        const { ctx } = this;
        let data = {};
        const user = await ctx.model.User.findById(userId);
        const role = await ctx.model.Role.findById(roleId);
        if (!user) {
            ctx.throw(404, '用户不存在');
        }
        if (!role) {
            ctx.throw(404, '角色不存在');
        }
        // 权限验证
        await ctx.powerValidate();
        if (destroy) {
            // 移除
            return await ctx.model.User.findByIdAndUpdate(userId, {
                $pull: {
                    role: roleId
                }
            });

        } else {
            // 新增
            return await ctx.model.User.findByIdAndUpdate(userId, {
                $addToSet: {
                    role: roleId
                }
            });
        }
    }
}

module.exports = UserService;
